package com.huangyi.rabbitmq_amqp.rpc;

import com.huangyi.rabbitmq_amqp.config.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        factory.setUsername(Constants.USER);
        factory.setPassword(Constants.PASSWORD);

        Connection connection = factory.newConnection();
        Channel channel  = connection.createChannel();

        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);

        String msg = "hello this is Controller";
        String id = UUID.randomUUID().toString();
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                        .correlationId(id)
                        .replyTo(Constants.RPC_RESPONSE_QUEUE)
                        .build();
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props,msg.getBytes());


        BlockingQueue<String> response =  new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("接收到消息" + msg);
                if(id.equals(properties.getCorrelationId())) {
                    response.offer(msg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String result = response.take();
        System.out.println("RPC Controller 响应结果" + result);
        channel.close();
        connection.close();
    }

}
